<template>
  <div class="app-detail-page" @scroll="onPageScroll">
    <a-page-header
      :title="detail.app_name"
      @back="() => $router.back()"
      style="padding: 0"
    >
      <div style="color: #000000a6" v-if="detail.app_desc">
        {{ detail.app_desc }}
      </div>
    </a-page-header>
    <template v-if="showPage">
      <a-tabs v-model:activeKey="currentTab" style="padding-top: 10px">
        <a-tab-pane key="setting" tab="设置"></a-tab-pane>
        <a-tab-pane key="release" tab="发布"></a-tab-pane>
        <a-tab-pane key="history" tab="对话记录"></a-tab-pane>
      </a-tabs>

      <div v-if="currentTab == 'setting'">
        <div class="flex">
          <div class="flex-1">
            <a-card
              title="基础信息"
              :bordered="false"
              style="width: 100%; border-radius: 6px"
            >
              <a-form-item
                label="应用ID"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <div style="display: flex; align-items: center">
                  <a-input v-model:value="detail.app_code" disabled />
                  <a-button
                    style="border-radius: 6px; margin-left: 10px"
                    @click="$utils.copyText(detail.app_code)"
                  >
                    <template #icon><CopyOutlined /></template>
                    复制
                  </a-button>
                </div>
              </a-form-item>

              <a-form-item
                label="应用图标"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <template #extra>
                  <div style="font-size: 12px">尺寸：120*120px</div>
                </template>
                <a-upload
                  :action="$utils.imgAction"
                  :headers="{ 'org-token': $store.getters.token }"
                  v-model:file-list="logoList"
                  @change="handleLogoUpload"
                  :multiple="true"
                  name="image"
                  :data="{ dir: 'work_ai' }"
                  accept="image/*"
                  list-type="picture-card"
                >
                  <div v-if="!logoList.length">
                    <PlusOutlined />
                    <div>上传图片</div>
                  </div>
                </a-upload>
              </a-form-item>

              <a-form-item
                label="应用名称"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-input v-model:value="detail.app_name" allowClear />
              </a-form-item>
              <a-form-item
                label="应用简介"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-textarea
                  v-model:value="detail.app_desc"
                  placeholder="请输入应用简介"
                  :rows="4"
                />
              </a-form-item>
            </a-card>

            <a-card
              title="角色资料"
              :bordered="false"
              style="width: 100%; border-radius: 6px; margin-top: 20px"
            >
              <a-form-item
                label="角色名称"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <template #extra>
                  <div style="padding-top: 5px; font-size: 12px">
                    以设定的角色进行对话，例如：AI 教练<br />要能够直接传达该角色的特征和风格，且不宜过于复杂
                  </div>
                </template>
                <a-input v-model:value="detail.role_name" allowClear />
              </a-form-item>
              <a-form-item
                label="角色介绍"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <div
                  class="absolute r-0"
                  style="top: -36px"
                  @click="autoGenerated('desc')"
                >
                  <a-button
                    size="small"
                    style="font-size: 12px"
                    :loading="descGeneratedLoading"
                    >AI一键生成</a-button
                  >
                </div>
                <a-textarea
                  v-model:value="detail.role_desc"
                  placeholder="请输入角色介绍"
                  :rows="6"
                  ref="descRef"
                />
              </a-form-item>
              <a-form-item
                label="欢迎语设置"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <div
                  class="absolute r-0"
                  style="top: -36px"
                  @click="autoGenerated('welcome')"
                >
                  <a-button
                    size="small"
                    style="font-size: 12px"
                    :loading="welcomeGeneratedLoading"
                    >AI一键生成</a-button
                  >
                </div>
                <a-textarea
                  v-model:value="detail.welcome_message"
                  placeholder="请输入欢迎语"
                  :rows="6"
                  ref="welcomeRef"
                />
              </a-form-item>
              <a-form-item
                label="角色设定Prompt"
                :labelCol="labelCol"
                :wrapperCol="{ span: 20 }"
              >
                <div
                  class="absolute r-0"
                  style="top: -36px"
                  @click="promptGeneratedVisible = true"
                >
                  <a-button
                    size="small"
                    style="font-size: 12px"
                    :loading="promptGeneratedLoading"
                    >AI一键生成</a-button
                  >
                </div>
                <a-textarea
                  v-model:value="detail.system_prompt"
                  placeholder="请输入角色设定Prompt"
                  :rows="10"
                  showCount
                  :maxlength="1200"
                  ref="systemPromptRef"
                />
                <template></template>
              </a-form-item>
            </a-card>

            <a-card
              title="对话相关"
              :bordered="false"
              style="width: 100%; border-radius: 6px; margin-top: 20px"
            >
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <template #label>
                  联想能力
                  <a-tooltip>
                    <template #title
                      >值越大回复内容越具多样性、创造性、随机性。值为0将根据事实回答，但同一个问题回复会重复，日常聊天建议0.5-0.8。</template
                    >
                    <QuestionCircleOutlined style="margin-left: 5px" />
                  </a-tooltip>
                </template>
                <a-slider
                  :marks="marks"
                  :min="0"
                  :max="2"
                  :step="0.1"
                  v-model:value="detail.temperature"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <template #label>
                  搜索相似度
                  <a-tooltip>
                    <template #title>高相似度推荐0.8及以上。</template>
                    <QuestionCircleOutlined style="margin-left: 5px" />
                  </a-tooltip>
                </template>
                <a-slider
                  :marks="{
                    0: 0,
                    1: 1,
                  }"
                  :min="0"
                  :max="1"
                  :step="0.01"
                  v-model:value="detail.rest.search_similarity"
                />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <template #label> 单次搜索数量 </template>
                <a-slider
                  :marks="{
                    1: 1,
                    20: 20,
                  }"
                  :min="1"
                  :max="20"
                  :step="1"
                  v-model:value="detail.rest.search_limit"
                />
              </a-form-item>
              <a-form-item
                label="绑定知识库"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-select
                  v-model:value="detail.related_wikis"
                  mode="multiple"
                  allowClear
                  style="width: 100%"
                  placeholder="请选择"
                  :options="
                    wikiList.map((item) => ({
                      label: item.name,
                      value: item.id,
                    }))
                  "
                  :getPopupContainer="getPopupContainer"
                >
                  <template #option="{ value, label }">
                    <div class="custom-select-wrap">
                      <span>{{ label }}</span>
                      <a-tooltip>
                        <template #title>在新标签中打开</template>
                        <div
                          class="open-icon"
                          @click.stop="openWikiData(value, label)"
                          :style="{
                            right: detail.related_wikis.includes(value)
                              ? '7px'
                              : '20px',
                          }"
                        >
                          <cu-icon
                            class="icon card-icon"
                            type="icon-dakai"
                          ></cu-icon>
                        </div>
                      </a-tooltip>
                    </div>
                  </template>
                  <template #dropdownRender="{ menuNode: menu }">
                    <v-nodes :vnodes="menu" />
                    <a-divider style="margin: 4px 0" />
                    <a-button
                      type="link"
                      style="padding: 0; margin: 0; display: block; width: 100%"
                      @mousedown="(e) => e.preventDefault()"
                      @click="addWiki"
                    >
                      <template #icon>
                        <PlusOutlined />
                      </template>
                      添加
                    </a-button>
                  </template>
                </a-select>
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                <template #label>
                  对话间隔
                  <a-tooltip>
                    <template #title
                      >如果超过对话间隔时间，会开启新的上下文。</template
                    >
                    <QuestionCircleOutlined style="margin-left: 5px" />
                  </a-tooltip>
                </template>
                <a-input
                  v-model:value="detail.rest.chat_effective_time"
                  style="width: 100px"
                  type="number"
                />
              </a-form-item>
              <a-form-item
                label="提问示例"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <template
                  v-if="
                    detail.introductory_word &&
                    detail.introductory_word.length > 0
                  "
                >
                  <template
                    v-for="(item, index) of detail.introductory_word"
                    :key="index"
                  >
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        margin-bottom: 8px;
                      "
                    >
                      <a-input
                        v-model:value="detail.introductory_word[index]"
                        allowClear
                        style=""
                      />
                      <DeleteOutlined
                        style="margin-left: 10px; cursor: pointer; color: #666"
                        @click="deleteExampleClick(index)"
                      />
                    </div>
                  </template>
                </template>
                <a-button
                  size="small"
                  style="border-radius: 6px"
                  @click="addExampleClick"
                  ><PlusOutlined />添加一组</a-button
                >
              </a-form-item>
              <a-form-item
                label="菜单栏"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <shortcuts
                  v-model:list="detail.shortcuts"
                  :limit="(detail.introductory_word || []).length > 0 ? 2 : 3"
                  @change="onSubmit"
                />
              </a-form-item>
              <!-- <a-form-item
                  label="联系我们"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-switch
                    v-model:checked="detail.is_contact_us"
                    :checkedValue="1"
                    :unCheckedValue="0"
                  />
                </a-form-item>
                <a-form-item
                  label="客服二维码"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <template #extra>
                    <div style="font-size: 12px">尺寸：240*240px</div>
                  </template>
                  <a-upload
                    :action="$utils.imgAction"
                    :headers="{ 'org-token': $store.getters.token }"
                    v-model:file-list="qrCodeList"
                    @change="handleQrCodeUpload"
                    :multiple="true"
                    name="image"
                    :data="{ dir: 'work_ai' }"
                    accept="image/*"
                    list-type="picture-card"
                  >
                    <div v-if="!qrCodeList.length">
                      <PlusOutlined />
                      <div>上传图片</div>
                    </div>
                  </a-upload>
                </a-form-item> -->
            </a-card>
            <a-affix :offset-bottom="affixBottom" style="margin-top: 20px">
              <a-card
                :bordered="false"
                style="
                  width: 100%;
                  border-radius: 6px;
                  border-top: 1px solid #f1f1f1;
                "
              >
                <a-button
                  type="primary"
                  @click="onSubmit"
                  style="border-radius: 6px"
                  >更新</a-button
                >
              </a-card>
            </a-affix>
          </div>
          <div class="app-viewer">
            <div class="app-box">
              <div class="app-box_header relative">
                {{ detail.app_name }}
                <ReloadOutlined
                  class="absolute"
                  @click="iframeReload"
                  style="right: 20px; top: 15px; font-size: 16px"
                />
              </div>
              <div class="app-box_body app-iframe">
                <iframe
                  :src="
                    detail.site_url +
                    '&receive=1&user_token=' +
                    $utils.getUserToken()
                  "
                  frameborder="0"
                  height="100%"
                  width="100%"
                  seamless="seamless"
                  v-if="iframeVisible"
                ></iframe>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="currentTab == 'release'">
        <a-card :bordered="false" style="width: 100%; border-radius: 6px">
          <div class="release-container">
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-web-icon">
                  <CuIcon class="iconfont" type="icon-wangye" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">网页</div>
                <div class="r-desc">用户在此链接可以直接和您的机器人聊天</div>
                <div class="r-set-container">
                  <div class="icon-set-container" @click="modalModel = 'web'">
                    <CuIcon class="iconfont" type="icon-fuzhi" /> 复制链接
                  </div>
                  <div
                    class="icon-set-container"
                    @click="openWebUrl(detail.site_url)"
                  >
                    <CuIcon class="iconfont" type="icon-yulan" /> 预览体验
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-gongzhonghao-icon">
                  <CuIcon class="iconfont" type="icon-gongzhonghao" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">微信公众号</div>
                <div class="r-desc">可在微信公众号后台配置，提供机器人服务</div>
                <div class="r-set-container">
                  <div
                    class="icon-set-container"
                    @click="modalModel = 'wechat'"
                  >
                    <CuIcon class="iconfont" type="icon-peizhi" /> 配置公众号
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-code-icon">
                  <CuIcon class="iconfont" type="icon-code" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">JS嵌入</div>
                <div class="r-desc">
                  可添加到网站的任何位置，将此 iframe 添加到 html 代码中
                </div>
                <div class="r-set-container">
                  <div
                    class="icon-set-container"
                    @click="onIframeDrawerVisible = true"
                  >
                    <CuIcon class="iconfont" type="icon-yulan" /> 查看代码
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-qy-kefu-icon">
                  <CuIcon class="iconfont" type="icon-kefu1" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">微信客服</div>
                <div class="r-desc">通过配置微信客服，实现与机器人1V1聊天</div>
                <div class="r-set-container">
                  <div
                    class="icon-set-container"
                    @click="onQyWechatKefuConfig('qy_kefu')"
                  >
                    <CuIcon class="iconfont" type="icon-fuzhi" /> 配置微信客服
                  </div>
                  <div
                    class="icon-set-container"
                    @click="
                      openWebUrl(
                        'https://e1enanjp674.feishu.cn/docx/OINrdH7xvoUgiZx8gtXcBvBHnzd'
                      )
                    "
                  >
                    <CuIcon class="iconfont" type="icon-shiyongwendang" />
                    配置文档
                  </div>
                  <div
                    class="icon-set-container"
                    v-if="detail?.rest?.qy_work?.corp_id"
                    @click="modalModel = 'qy_kefu_list'"
                  >
                    <CuIcon class="iconfont" type="icon-liebiaoxingshi" />
                    客服列表
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-api-icon">
                  <CuIcon class="iconfont" type="icon-api" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">API调用</div>
                <div class="r-desc">通过API，可直接进行调用或发出请求</div>
                <div class="r-set-container">
                  <!-- <div class="icon-set-container" @click="onNotActivatedModal">
                    <CuIcon class="iconfont" type="icon-peizhi" /> 配置接口
                  </div> -->
                  <div class="icon-set-container" @click="modalModel = 'api'">
                    <CuIcon class="iconfont" type="icon-yulan" /> 接口秘钥
                  </div>
                  <div
                    class="icon-set-container"
                    @click="
                      openWebUrl(
                        'https://apifox.com/apidoc/shared-5f48e599-6085-477f-a9d1-e306b1c8a778'
                      )
                    "
                  >
                    <CuIcon class="iconfont" type="icon-shiyongwendang" />
                    接口文档
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-qy-wechat-icon">
                  <CuIcon class="iconfont" type="icon-qiyeweixin" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">企业微信</div>
                <div class="r-desc">在企业微信中提供机器人服务</div>
                <div class="r-set-container">
                  <div
                    class="icon-set-container"
                    @click="onQyWechatKefuConfig('qy_wechat')"
                  >
                    <CuIcon class="iconfont" type="icon-peizhi" /> 配置企业微信
                  </div>
                  <div
                    class="icon-set-container"
                    @click="
                      openWebUrl(
                        'https://e1enanjp674.feishu.cn/docx/OHk5dAqw7o19Y8xxkxkchDaZnxh'
                      )
                    "
                  >
                    <CuIcon class="iconfont" type="icon-shiyongwendang" />
                    配置文档
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-feishu-icon">
                  <img :src="feishuIcon" class="iconfont" />
                  <!-- <CuIcon type="icon-xiaoxituisonglanse" /> -->
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">飞书</div>
                <div class="r-desc">在飞书群聊中提供机器人服务</div>
                <div class="r-set-container">
                  <div class="icon-set-container" @click="onNotActivatedModal">
                    <CuIcon
                      class="iconfont"
                      type="icon-peizhi"
                      style="font-size: 18px"
                    />
                    配置飞书
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-dingding-icon">
                  <CuIcon class="iconfont" type="icon-dingding" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">钉钉</div>
                <div class="r-desc">在钉钉中提供机器人服务</div>
                <div class="r-set-container">
                  <div class="icon-set-container" @click="onNotActivatedModal">
                    <CuIcon class="iconfont" type="icon-peizhi" /> 配置钉钉
                  </div>
                </div>
              </div>
            </div>
            <div class="release-container__box">
              <div class="release-container__box--left">
                <div class="r-icon r-group-chat-icon">
                  <CuIcon class="iconfont" type="icon-qunliao" />
                </div>
              </div>
              <div class="release-container__box--right">
                <div class="r-title">微信群聊</div>
                <div class="r-desc">在微信群聊中提供机器人服务</div>
                <div class="r-set-container">
                  <div class="icon-set-container" @click="onNotActivatedModal">
                    <CuIcon class="iconfont" type="icon-peizhi" /> 配置微信群聊
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </div>
      <div v-if="currentTab == 'history'">
        <a-card
          title="对话历史记录"
          :bordered="false"
          style="width: 100%; border-radius: 6px"
        >
          <a-table
            :dataSource="historyList"
            :columns="historyColumns"
            :pagination="pagination"
            @change="handleTableChange"
            rowKey="id"
            :bordered="true"
            size="small"
            :loading="historyLoading"
          >
            <template #question="{ record }">
              <div
                style="
                  overflow: hidden;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                "
              >
                {{ record.human }}
              </div>
            </template>
            <template #answer="{ record }">
              <div
                style="
                  overflow: hidden;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                "
              >
                {{ record.ai }}
              </div>
            </template>
            <template #action="{ record }">
              <a-button
                type="link"
                style="padding: 0; margin: 0"
                @click="onChatSearchSimilarityClick(record)"
                >相似度查询</a-button
              >
              <a-button
                type="link"
                style="padding: 0; margin-left: 5px"
                @click="historyCorrectClick(record)"
                >修正</a-button
              >
              <a-button
                type="link"
                style="padding: 0; margin-left: 5px"
                @click="historyDetailClick(record.chat.chat_id)"
                >查看上下文</a-button
              >
            </template>
            <template #expandedRowRender="{ record }">
              <ul class="expand-ul">
                <li>
                  <div class="expand-left">提问：</div>
                  <div class="markdow-answer-expand">{{ record.human }}</div>
                </li>
                <li>
                  <div class="expand-left">答案：</div>
                  <div class="markdow-answer-expand">{{ record.ai }}</div>
                </li>
              </ul>
            </template>
          </a-table>
        </a-card>
      </div>
    </template>

    <a-modal
      :visible="editWikiVisible"
      title="添加知识库"
      centered
      :width="400"
      @cancel="editWikiVisible = false"
      @ok="onSubmitWiki"
      ok-text="保存"
      :zIndex="1051"
    >
      <div class="modal-content">
        <a-input v-model:value="editWikiName" placeholder="知识库名称" />
      </div>
    </a-modal>

    <!-- 对话历史详情 -->
    <HistoryDetail
      :visible="historyDetailVisible"
      :chatId="historyDetailId"
      :aiAvatar="detail.app_logo"
      @onClose="historyDetailVisible = false"
    />

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />

    <!-- 开通会员套餐 -->
    <MemberShip :visible="memberShipVisible" @close="closeMemberShip" />

    <a-modal
      v-model:visible="kfModalVisible"
      :title="(kfModelRef.id ? '修改' : '新增') + '客服'"
      @cancel="onAddKfModalCancel"
      @ok="onAddKfModalOk"
      :confirmLoading="kfAddLoading"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="客服名称" v-bind="kfValidateInfos.name">
          <a-input v-model:value="kfModelRef.name" />
        </a-form-item>
        <a-form-item label="客服头像" v-bind="kfValidateInfos.avatar_url">
          <a-upload
            :action="$utils.imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            v-model:file-list="kfAvatarList"
            @change="handleKfAvatarUpload"
            :multiple="true"
            name="image"
            :data="{ dir: 'work_ai' }"
            accept="image/*"
            list-type="picture-card"
          >
            <div v-if="!kfAvatarList.length">
              <PlusOutlined />
              <div>上传头像</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      title="查看客服二维码"
      width="400px"
      v-model:visible="kfQrcodeModalVisible"
      :footer="null"
      @cancel="onKfGenQrcodeModalCancel"
    >
      <a-spin :spinning="kfQrcodeGenLading">
        <div class="flex justify-center flex-col">
          <div class="flex justify-center">
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
                width: 170px;
                height: 170px;
                border: 1px solid #d9d9d9;
                border-radius: 6px;
              "
            >
              <qrcode-vue
                :value="kfQrcodeUrl"
                :size="150"
                id="h5Qrcode"
                level="L"
              />
            </div>
          </div>
          <div
            style="
              display: flex;
              align-items: center;
              width: 300px;
              margin: 0 auto;
              margin-top: 20px;
            "
            v-if="kfQrcodeUrl"
          >
            <a-input v-model:value="kfQrcodeUrl" disabled />
            <a-button
              style="border-radius: 6px; margin-left: 10px"
              @click="$utils.copyText(kfQrcodeUrl)"
            >
              <template #icon><CopyOutlined /></template>
              复制
            </a-button>
          </div>
        </div>
      </a-spin>
    </a-modal>

    <a-modal
      :visible="importModalVisible"
      title="手动导入数据"
      @ok="importModalHandleOk()"
      @cancel="importModalVisible = false"
      width="40%"
      :confirm-loading="importModalConfirmLoading"
      okText="确认导入"
    >
      <div>
        <div class="mb-5">匹配的知识点</div>
        <a-input
          v-model:value="wikiState.question"
          placeholder="可以理解为问题。"
          :maxlength="3000"
        ></a-input>
      </div>
      <div class="mt-10">
        <div class="mb-5">补充知识</div>
        <a-textarea
          v-model:value="wikiState.answer"
          style="height: 300px; resize: none"
          placeholder="可以理解为需要训练的答案。"
          :maxlength="3000"
        ></a-textarea>
      </div>
      <div class="mt-10">
        <div class="mb-5">选择知识库</div>
        <a-select v-model:value="wikiState.wiki_id" style="width: 300px">
          <a-select-option
            v-for="item in wikiList.filter((wiki) =>
              detail.related_wikis.includes(wiki.id)
            )"
            :key="item.id"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </div>
    </a-modal>
    <PromptGeneratedModal
      v-model:role_name="detail.role_name"
      v-model:visible="promptGeneratedVisible"
      @start="onPromptGeneratedStart"
      @stream="onPromptGeneratedStream"
      @end="onPromptGeneratedEnd"
      ref="generatedRef"
    />

    <a-modal
      :visible="modalModel != null"
      @cancel="modalModel = null"
      :width="800"
      :title="modalTitle[modalModel] || false"
      @ok="onModalOk"
    >
      <template v-if="modalModel == 'web'">
        <header>是否开启</header>
        <p class="flex pt-15 pb-15">
          <a-switch
            checked-children="已发布"
            un-checked-children="已停用"
            v-model:checked="detail.is_release"
            :checkedValue="1"
            :unCheckedValue="0"
          />
        </p>
        <template v-if="detail.is_release">
          <header>匿名访问</header>
          <p class="flex pt-15 pb-15">
            <a-switch
              checked-children="允许"
              un-checked-children="禁用"
              v-model:checked="detail.allow_anonymous"
              :checkedValue="1"
              :unCheckedValue="0"
            />
          </p>
          <header>URL链接</header>
          <p class="flex align-center pt-15 pb-15">
            {{ detail.site_url }}
            <a-button
              style="margin-left: 10px"
              @click="$utils.copyText(detail.site_url)"
              type="link"
            >
              <template #icon><CopyOutlined /></template>
              复制
            </a-button>
          </p>
          <header>二维码</header>
          <div
            style="
              display: flex;
              justify-content: center;
              align-items: center;
              width: 170px;
              height: 170px;
              border: 1px solid #d9d9d9;
              border-radius: 6px;
            "
            v-if="detail.site_url"
            class="mt-15 mb-15"
          >
            <qrcode-vue
              :value="detail.site_url"
              :size="150"
              id="h5Qrcode"
              level="L"
            />
          </div>
        </template>
      </template>
      <template v-if="modalModel == 'qy_kefu' || modalModel == 'qy_wechat'">
        <div v-if="detail.rest.qy_work.corp_id">
          <header>企业ID</header>
          <div class="flex align-center justify-between mb-15">
            {{ detail.rest.qy_work.corp_id }}
            <a-button
              style="margin-left: 10px"
              @click="$utils.copyText(detail.rest.qy_work.corp_id)"
              type="link"
            >
              <template #icon><CopyOutlined /></template>
              复制
            </a-button>
          </div>
          <header>Secret</header>
          <div class="flex align-center justify-between mb-15">
            {{ detail.rest.qy_work.secret }}
            <a-button
              style="margin-left: 10px"
              @click="$utils.copyText(detail.rest.qy_work.secret)"
              type="link"
            >
              <template #icon><CopyOutlined /></template>
              复制
            </a-button>
          </div>
          <header>服务器配置</header>
          <div class="mt-10 mb-15">
            <div class="flex justify-between align-center">
              <label>回调URL: {{ detail.qy_work_url }}</label>
              <a-button
                style="margin-left: 10px"
                @click="$utils.copyText(detail.qy_work_url)"
                type="link"
              >
                <template #icon><CopyOutlined /></template>
                复制
              </a-button>
            </div>
            <div class="flex justify-between align-center">
              <label>Token: {{ detail.rest.qy_work.token }}</label>
              <a-button
                style="margin-left: 10px"
                @click="$utils.copyText(detail.rest.qy_work.token)"
                type="link"
              >
                <template #icon><CopyOutlined /></template>
                复制
              </a-button>
            </div>
            <div class="flex justify-between align-center">
              <label>EncodingAESKey: {{ detail.rest.qy_work.aes_key }}</label>
              <a-button
                style="margin-left: 10px"
                @click="$utils.copyText(detail.rest.qy_work.aes_key)"
                type="link"
              >
                <template #icon><CopyOutlined /></template>
                复制
              </a-button>
            </div>
          </div>
        </div>
        <div v-else>
          <header>企业微信扫码授权</header>
          <div class="mt-15 mb-15">
            <QyWechatAuth :appId="appId" @authed="onQyWechatAuthed" />
          </div>
        </div>
      </template>
      <template v-if="modalModel == 'qy_kefu_list'">
        <div class="mb-15">
          <a-button type="primary" size="small" @click="onAddKf">添加</a-button>
        </div>
        <a-table
          :dataSource="kfList"
          :columns="kfColumns"
          :pagination="kfPagination"
          @change="handleKfTableChange"
          rowKey="id"
          :bordered="true"
          size="small"
          :loading="kfLoading"
        >
          <template #userinfo="{ record }">
            {{ record.name }}
            <QrcodeOutlined
              style="margin-left: 5px; cursor: pointer"
              @click="genAppKfQrcode(record.id)"
            />
          </template>
          <template #action="{ record }">
            <a-button
              type="link"
              style="padding: 0; margin: 0"
              @click="kfEditClick(record)"
              >修改</a-button
            >
            <a-popconfirm
              title="删除后无法恢复，确认删除吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="kfDeleteClick(record.id)"
            >
              <a-button type="link" style="padding: 0; margin-left: 10px"
                >删除</a-button
              >
            </a-popconfirm>
          </template>
        </a-table>
      </template>
      <template v-if="modalModel == 'wechat'">
        <a-tabs v-model:activeKey="wechatActiveKey">
          <a-tab-pane key="menu" tab="添加菜单">
            <a-button
              type="link"
              @click="wechatMenuVisible = true"
              style="font-size: 16px"
              >查看填写示意图</a-button
            >
            <div class="mt-10">
              <a-steps direction="vertical" :current="3">
                <a-step status="wait">
                  <template #title>
                    <p style="font-size: 16px">
                      进入微信
                      <a
                        href="https://mp.weixin.qq.com/"
                        target="_blank"
                        style="color: #29c74a"
                        >「公众号后台」</a
                      >
                    </p>
                  </template>
                  <template #description>
                    <p>请确保您的公众号已过微信认证</p>
                    <p>路径：内容与互动 > 自定义菜单 > 添加菜单</p>
                  </template>
                </a-step>
                <a-step status="wait">
                  <template #title>
                    <p style="font-size: 16px">创建菜单</p>
                  </template>
                  <template #description>
                    <p>填写菜单名称，将以下链接或二维码，配置到菜单里</p>
                    <p>{{ detail.site_url }}</p>
                    <p>
                      <a-button
                        type="link"
                        style="padding-left: 0px"
                        @click="$utils.copyText(detail.site_url)"
                        >复制链接</a-button
                      >
                      <a :href="siteUrlQrcode" download="二维码">
                        <a-button type="link" style="padding-left: 0px"
                          >下载二维码</a-button
                        >
                      </a>
                    </p>
                  </template>
                </a-step>
              </a-steps>
            </div>
          </a-tab-pane>
        </a-tabs>
      </template>
      <template v-if="modalModel == 'api'">
        <p>
          机器人标识：{{ detail.app_code }}
          <a-button type="link" @click="$utils.copyText(detail.app_code)"
            >复制</a-button
          >
        </p>
        <p>
          token：{{ detail.token }}
          <a-button type="link" @click="$utils.copyText(detail.app_code)"
            >复制</a-button
          >
        </p>
      </template>
      <template
        #footer
        v-if="
          ['qy_kefu', 'qy_kefu_list', 'wechat', 'wechat_menu', 'api'].includes(
            modalModel
          )
        "
      >
        <div></div>
      </template>
    </a-modal>

    <a-modal v-model:visible="wechatMenuVisible" :footer="false" :width="800">
      <img src="../../common/image/addMenuTabImg.png" class="w-full h-full" />
    </a-modal>

    <a-drawer
      title="查看代码"
      placement="right"
      :closable="false"
      width="40%"
      v-model:visible="onIframeDrawerVisible"
    >
      <div>
        <header>JS代码</header>
        <p class="mt-10" style="font-size: 12px; color: #606266">
          机器人代码，请将此 iframe 添加到您的 html 代码中
        </p>
        <div style="position: relative">
          <markdown-viewer :markdown="iframeMarkdownHtml" />
          <a-button
            type="link"
            style="
              position: absolute;
              right: 0px;
              top: 0px;
              color: #fff;
              padding-right: 5px;
            "
            @click="
              $utils.copyText(
                `<iframe src=&quot;${detail.iframe_url}&quot; width=&quot;408px&quot; height=&quot;594px&quot; frameborder=&quot;0&quot;>\n</iframe>`
              )
            "
            >Copy</a-button
          >
        </div>
        <p class="mt-10" style="font-size: 12px; color: #606266">
          添加聊天气泡，请复制添加到您的 html中
        </p>
        <!-- <div style="position: relative">
          <markdown-viewer :markdown="iframePopupMarkdownHtml" />
          <a-button
            type="link"
            style="
              position: absolute;
              right: 0px;
              top: 0px;
              color: #fff;
              padding-right: 5px;
            "
            @click="
              $utils.copyText(
                `<script>\nwindow.tip_cby_color=&quot;#fff&quot;;\nwindow.tip_cby_bg=&quot;#4C83F3&quot;;\nwindow.cby_iframe_src = &quot;${detail.iframe_url}&quot;;\nvar st = document.createElement(&quot;script&quot;);\nst.type=&quot;text/javascript&quot;;\nst.async = true;\nst.src = &quot;https://chato.cn/assets/iframe.min.js&quot;;\nvar header = document.getElementsByTagName(&quot;head&quot;)[0];\nheader.appendChild(st);</script>`
              )
            "
            >Copy</a-button
          >
        </div> -->
      </div>
    </a-drawer>
    <app-chat-search-similarity
      :app_id="appId"
      v-model:visible="appChatSearchSimilarityVisible"
      :question="appChatSearchSimilarityQuestion"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
  ref,
  nextTick,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message, Form } from "ant-design-vue";
import {
  WarningFilled,
  PlusCircleOutlined,
  SwapOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  DeleteOutlined,
  CopyOutlined,
  ReloadOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import QrcodeVue from "qrcode.vue";
import HistoryDetail from "./modules/HistoryDetail.vue";
import MemberShip from "../../views/vip/modules/memberShip.vue";
import QyWechatAuth from "./modules/QyWechatAuth.vue";
import PromptGeneratedModal from "../../components/PromptGenerated/modal.vue";
import QRCode from "qrcode";
import MarkdownViewer from "../../components/MarkdownViewer/index.vue";
import defaultSetting from "../../common/utils/defaultSetting";
import feishuIcon from "../../common/image/feishu-icon.png";
import AppChatSearchSimilarity from "../../components/AppChatSearchSimilarity/drawer.vue";
import Shortcuts from "./modules/Shortcuts.vue";

const useForm = Form.useForm;

export default defineComponent({
  name: "Create",
  components: {
    PlusOutlined,
    DeleteOutlined,
    CopyOutlined,
    ReloadOutlined,
    QuestionCircleOutlined,
    QrcodeVue,
    HistoryDetail,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    MemberShip,
    PromptGeneratedModal,
    QyWechatAuth,
    MarkdownViewer,
    AppChatSearchSimilarity,
    Shortcuts,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      loginVisible: false,
      showPage: false,

      detail: { rest: {}, shortcuts: [], introductory_word: [] },
      currentTab: "setting",
      labelCol: { span: 24 },
      wrapperCol: { span: 12 },
      logoList: [],
      qrCodeList: [],
      affixBottom: 0,

      total: 0,
      page: 1,
      pageSize: 20,
      historyLoading: false,
      historyList: [],
      historyColumns: [
        {
          title: "提问",
          align: "left",
          width: "25%",
          slots: {
            customRender: "question",
          },
        },
        {
          title: "回答",
          align: "left",
          width: "25%",
          slots: {
            customRender: "answer",
          },
        },
        {
          title: "提问者",
          dataIndex: "chat.user.nickname",
          width: "14%",
          align: "center",
        },
        {
          title: "创建时间",
          dataIndex: "created_at",
          width: "18%",
          align: "center",
        },
        {
          title: "操作",
          slots: {
            customRender: "action",
          },
          width: "18%",
          align: "center",
        },
      ],
      historyDetailId: 0,
      historyDetailVisible: false,

      wikiList: [],
      editWikiName: "",
      editWikiVisible: false,
      memberShipVisible: false,
    });

    const siteUrlQrcode = ref("");

    const getDetail = () => {
      request
        .get("/work_ai", "/user/team/app/detail", {
          id: route.query.id,
        })
        .then(async (res) => {
          if (res.data && res.data.id) {
            if (!res.data.related_wikis) {
              res.data.related_wikis = [];
            }
            state.detail = res.data;
            if (res.data.app_logo) {
              state.logoList = [
                {
                  uid: 1,
                  name: res.data.app_logo,
                  status: "done",
                  url: res.data.app_logo,
                },
              ];
            }
            if (res.data.contact_qrcode) {
              state.qrCodeList = [
                {
                  uid: 1,
                  name: res.data.contact_qrcode,
                  status: "done",
                  url: res.data.contact_qrcode,
                },
              ];
            }

            siteUrlQrcode.value = await QRCode.toDataURL(state.detail.site_url);
          }
        });
    };

    const init = () => {
      if (route.query.id) {
        getDetail();
        getHistoryList();
        getWikiList();
        getKfList();
      }
    };

    utils.checkLogin().then((isLogin) => {
      if (!isLogin) {
        state.loginVisible = true;
        return;
      }
      state.showPage = true;
      init();
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    const onStatusChange = (checked) => {
      request
        .patch("/work_ai", "/user/team/app/release", {
          id: route.query.id,
          is_release: checked ? 1 : 0,
        })
        .then((res) => {
          if (checked) {
            message.success("发布成功");
          } else {
            message.success("停用成功");
          }
        })
        .catch((err) => {
          state.detail.is_release = !checked ? 1 : 0;
          if (err.code == 3601) {
            message.warn(err.msg);
            state.memberShipVisible = true;
          }
        });
    };

    // 上传图片(应用图标)
    const handleLogoUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.logoList = resFileList;
      if (state.logoList.length) {
        state.detail.app_logo = state.logoList[0].url;
      } else {
        state.detail.app_logo = "";
      }
    };

    const addExampleClick = () => {
      if (state.detail.introductory_word) {
        state.detail.introductory_word.push("");
      } else {
        state.detail.introductory_word = [""];
      }
    };

    const deleteExampleClick = (index) => {
      state.detail.introductory_word.splice(index, 1);
    };

    // 上传图片(客服二维码)
    const handleQrCodeUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.qrCodeList = resFileList;
      if (state.qrCodeList.length) {
        state.detail.contact_qrcode = state.qrCodeList[0].url;
      } else {
        state.detail.contact_qrcode = "";
      }
    };

    const onPageScroll = (e) => {
      let scrollTop = e.target.scrollTop; //滑入屏幕滚动条滚动时，距离顶部的距离
      let windowHeitht = e.target.clientHeight; //能看到的页面的高度
      let scrollHeight = e.target.scrollHeight; //监控的整个div的高度（包括现在看到的和上下隐藏起来看不到的）
      let total = scrollTop + windowHeitht;
      if (total + 20 >= scrollHeight) {
        // console.log("到底了");
        state.affixBottom = 20;
      } else {
        // console.log("还没有到底");
        state.affixBottom = 0;
      }
    };

    const onSubmit = () => {
      let params = {
        id: route.query.id,
        app_name: "",
        app_logo: "",
        app_desc: "",
        role_name: "",
        role_desc: "",
        temperature: "",
        welcome_message: "",
        system_prompt: "",
        introductory_word: [],
        is_contact_us: null,
        contact_qrcode: "",
        is_release: null,
        allow_anonymous: null,
        related_wikis: [],
        rest: [],
        shortcuts: [],
      };
      for (let key in params) {
        params[key] = state.detail[key];
      }
      request
        .put("/work_ai", "/user/team/app", {
          ...params,
        })
        .then((res) => {
          message.success("保存成功");
          init();
          iframeReload();
        });
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getHistoryList();
    };

    const getHistoryList = () => {
      state.historyLoading = true;
      let params = {
        page: state.page,
        pageSize: 15,
        app_id: route.query.id,
      };

      request
        .get("/work_ai", "/user/team/app/chat/question", { ...params })
        .then((res) => {
          state.historyLoading = false;
          if (res.list) {
            state.historyList = res.list;
          }
          state.total = res.total;
        });
    };

    const historyDetailClick = (id) => {
      state.historyDetailId = id;
      state.historyDetailVisible = true;
    };

    const getWikiList = () => {
      request
        .get("/work_ai", "/user/team/wiki", {
          page: 1,
          pageSize: 9999,
          team_id: store.state.user.teamId,
        })
        .then((res) => {
          if (res.list) {
            state.wikiList = res.list;
          }
        });
    };

    const addWiki = () => {
      state.editWikiName = "";
      state.editWikiVisible = true;
    };

    const onSubmitWiki = () => {
      if (!state.editWikiName) {
        message.error("知识库名称不能为空");
        return;
      }

      let requestType = "post";
      let url = "/user/team/wiki";
      let params = {
        name: state.editWikiName,
        team_id: store.state.user.teamId,
      };
      request[requestType]("/work_ai", url, {
        ...params,
      }).then((res) => {
        message.success("添加成功");
        state.editWikiVisible = false;
        getWikiList();
      });
    };

    const closeMemberShip = () => {
      state.memberShipVisible = false;
    };

    const openWikiData = (id, name) => {
      let baseUrl = location.origin;
      if (process.env.NODE_ENV === "development") {
        baseUrl = "https://chatgpt.kuaijingai.com";
      }
      let url = `${baseUrl}/#/training/setting/wikiData?wiki_id=${id}&name=${name}`;
      window.open(url);
    };

    const getPopupContainer = (trigger) => {
      return trigger.parentNode;
    };

    const iframeVisible = ref(true);

    const iframeReload = () => {
      iframeVisible.value = false;

      nextTick(() => {
        iframeVisible.value = true;
      });
    };

    const marks = ref({
      0: "最精确",
      0.5: "较精确",
      1: "平衡",
      1.5: "强创能力",
      2: "天马星空",
    });

    const kfList = ref([]);
    const kfColumns = [
      {
        title: "客服名称",
        dataIndex: "name",
        slots: { customRender: "userinfo" },
      },
      {
        title: "操作",
        align: "center",
        width: "120px",
        slots: { customRender: "action" },
      },
    ];

    const kfState = reactive({
      total: 0,
      page: 1,
      pageSize: 5,
    });

    const kfLoading = ref(false);

    const kfPagination = computed(() => ({
      total: kfState.total,
      current: kfState.page,
      pageSize: kfState.pageSize,
      showSizeChanger: true,
    }));

    const handleKfTableChange = (pager, filters, sorter) => {
      kfState.page = pager.current;
      kfState.pageSize = pager.pageSize;
      getKfList();
    };

    const getKfList = () => {
      kfLoading.value = true;

      let params = {
        page: kfState.page,
        pageSize: kfState.pageSize,
        app_id: route.query.id,
      };

      request
        .get("/work_ai", "/user/team/app/qykf", { ...params })
        .then((res) => {
          kfLoading.value = false;

          if (res.list) {
            kfList.value = res.list;
          }

          kfState.total = res.total;
        });
    };

    const kfModalVisible = ref(false);
    const kfModelRef = reactive({
      id: "",
      name: "",
      avatar_url: "",
    });

    const kfRulesRef = reactive({
      name: [
        {
          required: true,
          message: "请输入客服名称",
        },
      ],
      avatar_url: [
        {
          required: true,
          message: "请上传客服头像",
        },
      ],
    });

    const kfAvatarList = ref([]);

    const {
      resetFields: resetKfFields,
      validate: kfValidate,
      validateInfos: kfValidateInfos,
    } = useForm(kfModelRef, kfRulesRef);

    const onAddKf = () => {
      kfModalVisible.value = true;
    };

    const handleKfAvatarUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      kfAvatarList.value = resFileList;
      if (kfAvatarList.value.length) {
        kfModelRef.avatar_url = kfAvatarList.value[0].url;
      } else {
        kfModelRef.avatar_url = "";
      }
    };

    const onAddKfModalCancel = () => {
      kfAvatarList.value = [];
      kfAddLoading.value = false;
      resetKfFields();
      kfModalVisible.value = false;
    };

    const kfAddLoading = ref(false);

    const onAddKfModalOk = () => {
      kfValidate().then(() => {
        kfAddLoading.value = true;

        const httpRequest = kfModelRef.id ? request.patch : request.post;

        httpRequest("/work_ai", "/user/team/app/qykf", {
          app_id: route.query.id,
          name: kfModelRef.name,
          avatar_url: kfModelRef.avatar_url,
          ...(kfModelRef.id ? { id: kfModelRef.id } : {}),
        })
          .then((res) => {
            message.success((kfModelRef.id ? "修改" : "新增") + "成功");
            onAddKfModalCancel();
            getKfList();
          })
          .catch((err) => {
            console.log(err);
            kfAddLoading.value = false;
          });
      });
    };

    const kfEditClick = (record) => {
      kfModalVisible.value = true;

      kfModelRef.id = record.id;
      kfModelRef.name = record.name;
      kfModelRef.avatar_url = record.avatar_url;

      kfAvatarList.value = [
        {
          uid: 1,
          name: record.avatar_url,
          status: "done",
          url: record.avatar_url,
        },
      ];
    };

    const kfDeleteClick = (id) => {
      request
        .del("/work_ai", "/user/team/app/qykf", {
          id,
        })
        .then((res) => {
          message.success("删除成功");
          getKfList();
        });
    };

    const kfQrcodeUrl = ref("");
    const kfQrcodeGenLading = ref(false);
    const kfQrcodeModalVisible = ref(false);

    const genAppKfQrcode = (id) => {
      kfQrcodeModalVisible.value = true;
      kfQrcodeGenLading.value = true;

      request
        .post("/work_ai", "/user/team/app/qykf/qrcode", {
          id,
        })
        .then(({ data: { url } }) => {
          console.log(url);
          kfQrcodeUrl.value = url;
          kfQrcodeGenLading.value = false;
        });
    };

    const onKfGenQrcodeModalCancel = () => {
      kfQrcodeUrl.value = "";
      kfQrcodeGenLading.value = false;
      kfQrcodeModalVisible.value = false;
    };

    const onQyWechatAuthed = () => {
      getDetail();
    };

    const generatedRef = ref(null);
    const systemPromptRef = ref(null);
    const descRef = ref(null);
    const welcomeRef = ref(null);

    const promptGeneratedVisible = ref(false);

    const promptGenerated = ref("");
    const descGenerated = ref("");
    const welcomeGenerated = ref("");

    const promptGeneratedLoading = ref(false);
    const descGeneratedLoading = ref(false);
    const welcomeGeneratedLoading = ref(false);

    const onPromptGeneratedStart = (type) => {
      if (type == "prompt") {
        promptGenerated.value = "";
        promptGeneratedLoading.value = true;
      } else if (type == "desc") {
        descGenerated.value = "";
        descGeneratedLoading.value = true;
      } else if (type == "welcome") {
        welcomeGenerated.value = "";
        welcomeGeneratedLoading.value = true;
      }
    };

    const onPromptGeneratedEnd = ({ type }) => {
      if (type == "prompt") {
        promptGeneratedLoading.value = false;
      } else if (type == "desc") {
        descGeneratedLoading.value = false;
      } else if (type == "welcome") {
        welcomeGeneratedLoading.value = false;
      }
    };

    const scrollToBottom = (type) => {
      let input;
      if (type == "prompt") {
        input = systemPromptRef.value.$el.querySelector(".ant-input");
      } else if (type == "desc") {
        input = descRef.value.$el;
      } else if (type == "welcome") {
        input = welcomeRef.value.$el;
      }

      input.scrollTop = input.scrollHeight;
    };

    const onPromptGeneratedStream = ({ text, type }) => {
      if (type == "prompt") {
        if (!promptGenerated.value) {
          state.detail.system_prompt = "";
          promptGeneratedVisible.value = false;
        }

        promptGenerated.value += text;
        state.detail.system_prompt += text;
      } else if (type == "desc") {
        if (!descGenerated.value) {
          state.detail.role_desc = "";
        }

        descGenerated.value += text;
        state.detail.role_desc += text;
      } else if (type == "welcome") {
        if (!welcomeGenerated.value) {
          state.detail.welcome_message = "";
        }

        welcomeGenerated.value += text;
        state.detail.welcome_message += text;
      }

      scrollToBottom(type);
    };

    const autoGenerated = async (type) => {
      let role_prompt = (state.detail.system_prompt || "").trim();

      if (!role_prompt) {
        promptGeneratedVisible.value = true;
        return;
      }

      onPromptGeneratedStart(type);

      const responseText = await generatedRef.value.generate(
        type,
        {
          role_prompt,
        },
        (text) => {
          onPromptGeneratedStream({
            text,
            type,
          });
        }
      );

      onPromptGeneratedEnd({ type, text: responseText });
    };

    const modalModel = ref(null);
    const modalTitle = {
      web: "复制链接",
      qy_kefu: "配置微信客服",
      qy_wechat: "配置企业微信",
      qy_kefu_list: "客服列表",
      wechat: "公众号配置",
      api: "查看秘钥",
    };

    const onModalOk = () => {
      if (modalModel.value == "web") {
        onSubmit();
        return;
      }

      modalModel.value = null;
    };

    const openWebUrl = (url) => {
      window.open(url);
    };

    const onQyWechatKefuConfig = (mode) => {
      if (!state.detail.open_qy_word) {
        message.warning("该功能未开通，请联系客服开通");
        return;
      }

      modalModel.value = mode;
    };

    const wechatActiveKey = ref("menu");
    const wechatMenuVisible = ref(false);
    const onIframeDrawerVisible = ref(false);
    const onNotActivatedModal = () => {
      message.warning("即将开放，敬请期待");
    };

    const iframeMarkdownHtml = computed(() => {
      return (
        '```html\n<iframe\nsrc="' +
        state.detail.iframe_url +
        '"\nwidth="408px"\nheight="594px"\nframeborder="0">\n</iframe>\n```'
      );
    });

    const baseUrl = `${
      utils.isEnv()
        ? `http://localhost:${location.port}`
        : defaultSetting.requestDomain
    }`;

    const iframePopupMarkdownHtml = computed(() => {
      return (
        '```javascript\n<script>\nwindow.tip_cby_color="#fff";\nwindow.tip_cby_bg="#4C83F3";\nwindow.cby_iframe_src = "' +
        state.detail.iframe_url +
        '";\nvar st = document.createElement("script");\nst.type="text/javascript";\nst.async = true;\nst.src = "' +
        baseUrl +
        '/assets/iframe.min.js";\nvar header = document.getElementsByTagName("head")[0];\nheader.appendChild(st);<' +
        "/" +
        "script>\n```"
      );
    });

    const importModalVisible = ref(false);
    const importModalConfirmLoading = ref(false);
    const wikiState = reactive({
      question: "",
      answer: "",
      wiki_id: "",
    });

    const historyCorrectClick = (record) => {
      wikiState.question = record.human;
      wikiState.answer = record.ai;

      if (state.detail.related_wikis.length > 0) {
        wikiState.wiki_id = state.detail.related_wikis[0];
      }

      importModalVisible.value = true;
    };

    const importModalHandleOk = () => {
      if (!wikiState.question) {
        return message.error("请填写匹配的知识点");
      }

      if (!wikiState.wiki_id) {
        return message.error("请选择知识库");
      }

      let params = {
        ...wikiState,
        team_id: store.state.user.teamId,
      };

      importModalConfirmLoading.value = true;
      request
        .post("/work_ai", "/user/team/wiki/data", params)
        .then(() => {
          importModalConfirmLoading.value = false;
          importModalVisible.value = false;

          message.success("导入成功");
        })
        .catch((err) => {
          importModalConfirmLoading.value = false;
        });
    };

    watch(importModalVisible, (val) => {
      if (!val) {
        wikiState.question = "";
        wikiState.answer = "";
        wikiState.wiki_id = "";
      }
    });

    const appChatSearchSimilarityVisible = ref(false);
    const appChatSearchSimilarityQuestion = ref("");

    watch(appChatSearchSimilarityVisible, (val) => {
      if (!val) {
        appChatSearchSimilarityQuestion.value = "";
      }
    });

    const onChatSearchSimilarityClick = (record) => {
      appChatSearchSimilarityQuestion.value = record.human;
      appChatSearchSimilarityVisible.value = true;
    };

    return {
      ...toRefs(state),
      loginCallback,
      onStatusChange,
      handleLogoUpload,
      addExampleClick,
      deleteExampleClick,
      handleQrCodeUpload,
      onSubmit,
      onPageScroll,
      pagination,
      handleTableChange,
      historyDetailClick,
      addWiki,
      onSubmitWiki,
      closeMemberShip,
      openWikiData,
      getPopupContainer,
      iframeVisible,
      iframeReload,
      marks,
      kfColumns,
      kfList,
      kfPagination,
      handleKfTableChange,
      kfLoading,
      onAddKf,
      kfValidateInfos,
      kfModalVisible,
      kfModelRef,
      handleKfAvatarUpload,
      kfAvatarList,
      onAddKfModalCancel,
      onAddKfModalOk,
      kfDeleteClick,
      kfAddLoading,
      kfEditClick,
      genAppKfQrcode,
      kfQrcodeUrl,
      kfQrcodeModalVisible,
      kfQrcodeGenLading,
      onKfGenQrcodeModalCancel,
      onQyWechatAuthed,
      appId: route.query.id,
      importModalVisible,
      importModalConfirmLoading,
      importModalHandleOk,
      wikiState,
      historyCorrectClick,
      promptGeneratedLoading,
      promptGeneratedVisible,
      onPromptGeneratedStart,
      onPromptGeneratedStream,
      systemPromptRef,
      modalModel,
      modalTitle,
      onModalOk,
      openWebUrl,
      onQyWechatKefuConfig,
      wechatActiveKey,
      wechatMenuVisible,
      onNotActivatedModal,
      siteUrlQrcode,
      onIframeDrawerVisible,
      iframeMarkdownHtml,
      iframePopupMarkdownHtml,
      defaultSetting,
      feishuIcon,
      appChatSearchSimilarityVisible,
      appChatSearchSimilarityQuestion,
      onChatSearchSimilarityClick,
      generatedRef,
      descGeneratedLoading,
      welcomeGeneratedLoading,
      onPromptGeneratedEnd,
      descRef,
      welcomeRef,
      autoGenerated,
    };
  },
});
</script>

<style lang="less" scoped>
.app-detail-page {
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow: hidden auto;
}

.app-detail-page :deep(.ant-page-header-content) {
  padding-top: 0px;
}

:deep(.ant-select-item-option) {
}

:deep(.custom-select-wrap) {
  position: relative;
  display: flex;
  align-items: center;

  .open-icon {
    visibility: hidden;
    position: absolute;
    top: 0;
    padding: 5px;
    background-color: #dddede;
    border-radius: 4px;
    font-size: 12px;
    color: #666;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &:hover {
    .open-icon {
      visibility: visible;
    }
  }
}

@appViewWidth: 600px;
@appBoxWidth: 375px;
@appBoxHeight: 667px;

.app-viewer {
  width: @appViewWidth;
}

.app-box {
  background: #f7f8fa;
  border-radius: 20px;

  position: fixed;
  right: calc((@appViewWidth - @appBoxWidth) / 2);
  bottom: 20px;

  &_header {
    height: 48px;
    line-height: 48px;
    background-color: #705df7;
    color: #fff;
    font-weight: 700;
    text-align: center;

    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
  }
}

.app-iframe {
  width: @appBoxWidth;
  height: @appBoxHeight;
  background: #f6f6f6;
  border: 1px solid #e1e1e1;
  border-top: none;
}

ul.expand-ul {
  padding: 10px;

  li {
    display: flex;
    margin-bottom: 10px;

    .expand-left {
      width: 50px;
      margin-right: 10px;
      flex-shrink: 0;
      color: #303133;
      font-weight: 700;
    }

    .markdow-answer-expand {
      line-height: 20px;
      margin-top: -3px;
    }
  }
}

.release-container {
  width: 90%;
  max-width: 1200px;
  // margin: 0 auto;

  padding-bottom: 20px;
  min-height: 100%;
  height: auto;

  &::after {
    content: "";
    display: block;
    clear: both;
  }

  &__box {
    width: 45%;

    overflow: hidden;
    box-sizing: border-box;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    float: left;
    padding: 20px;
    margin: 0 20px 20px 0;
    border-radius: 8px;
    border: 1px solid #e4e7ed;

    &--left {
      margin-right: 8px;
      font-size: 40px;
    }

    .r-icon {
      width: 1em;
      height: 1em;

      background: rgb(255, 101, 98);
      border-radius: 50%;

      display: flex;
      justify-content: center;
      align-items: center;
    }

    .r-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .r-desc {
      margin: 10px 0 24px;
      font-size: 12px;
      color: #9da3af;
      letter-spacing: 0.13px;
      line-height: 16px;
    }

    .r-set-container {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-top: 24px;

      .icon-set-container {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        gap: 8px;
        cursor: pointer;
        color: #b5bed0;
        margin-right: 16px;

        .iconfont {
          font-size: 14px;
        }
      }
    }

    .r-web-icon {
      background: #e0eaff;

      .iconfont {
        font-size: 20px;
      }
    }

    .r-qy-kefu-icon {
      background: #f1eefe;

      .iconfont {
        font-size: 20px;
      }
    }

    .r-gongzhonghao-icon {
      background: #e0fff8;

      .iconfont {
        font-size: 26px;
      }
    }

    .r-code-icon {
      background: #e0fff8;

      .iconfont {
        font-size: 22px;
      }
    }

    .r-api-icon {
      background: #f1eefe;

      .iconfont {
        font-size: 20px;
      }
    }

    .r-group-chat-icon {
      background: #e0eaff;

      .iconfont {
        font-size: 24px;
      }
    }

    .r-qy-wechat-icon {
      background: #e0eaff;

      .iconfont {
        font-size: 26px;
      }
    }

    .r-dingding-icon {
      background: #e0eaff;

      .iconfont {
        font-size: 26px;
      }
    }

    .r-feishu-icon {
      background: #e0eaff;

      .iconfont {
        width: 100%;
        height: 100%;
        padding: 6px;
      }
    }
  }
}

@media (max-width: 960px) {
  .release-container__box {
    width: 100% !important;
    margin: 0 0px 20px 0;
  }
}

header {
  color: #303133;
  font-size: 14px;
  line-height: 24px;
}

label {
  cursor: pointer;
  color: #5a6780;
}
</style>
